package com.chat.http.intercepter;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import com.chat.util.ResponseUtil;
import com.chat.vo.params.ExceptionVo;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 全局异常处理器
 * 
 * @author lwh
 *
 */
public class ExceptionInterceptor extends SimpleMappingExceptionResolver {

	@Override
	protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		try {

			ExceptionVo systemException = null;
			if (ex instanceof ExceptionVo) {
				systemException = (ExceptionVo) ex;
			} else {
				systemException = new ExceptionVo("未知错误");
			}

			PrintWriter out = ResponseUtil.responseJSON(response);
			Map<String, String> map = new HashMap<String, String>();
			map.put("status", "error");
			map.put("msg", systemException.getMessage());
			out.write(new ObjectMapper().writeValueAsString(map));
			out.flush();
			out.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	protected String findMatchingViewName(Properties exceptionMappings, Exception ex) {
		String msg = null;
		System.out.println(msg = super.findMatchingViewName(exceptionMappings, ex));
		return msg;
	}

}
